package com.ydy.ewallet.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 全局过滤器
 *
 * @author Kephon
 */
@Slf4j
@WebFilter(filterName = "globalFilter", urlPatterns = "/*")
public class GlobalFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("Global Filter inited...");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        StringBuilder url = new StringBuilder();
        for (Map.Entry<String, String[]> entry : request.getParameterMap().entrySet()) {
            String key = entry.getKey();
            String[] values = entry.getValue();

            for (String value : values) {
                // 防止过长的日志输出内容
                if (value.length() > 100) {
                    value = value.substring(0, 100);
                }
                url.append(key).append("=").append(value).append("&");
            }
        }

        log.info("--- {}?{}\tSessionId: {}", request.getRequestURI(), url.toString(), request.getSession().getId());

        filterChain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy() {
        log.info("Global Filter destroyed...");
    }

}
